package de.sonntagsfarben.puremvc.as3.modules
{
	import de.sonntagsfarben.puremvc.as3.modules.model.vo.ModuleVO;

	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	/**
	 * @author Soenke Kluth <sonntagsfarben.de>
	 */
	public class ModuleLoader extends Sprite
	{
		public static const COMPLETE : String = "READY";
		private var _module : IModule;
		public var _moduleVO : ModuleVO;

		public function ModuleLoader()
		{
		}

		public function load( moduleVO : ModuleVO ) : void
		{
			var loader : Loader = new Loader();
			_moduleVO = moduleVO;
			loader.contentLoaderInfo.addEventListener( Event.COMPLETE , onComplete , false , 0 , true );
			loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR , onIOError , false , 0 , true );
			loader.contentLoaderInfo.addEventListener( ProgressEvent.PROGRESS , onProgress , false , 0 , true );
			var loaderContext : LoaderContext = new LoaderContext( true );
			loader.load( new URLRequest( moduleVO.url ) , loaderContext );
		}

		protected function removeListeners( loader : LoaderInfo ) : void
		{
			loader.removeEventListener( Event.COMPLETE , onComplete );
			loader.removeEventListener( IOErrorEvent.IO_ERROR , onIOError );
			loader.removeEventListener( ProgressEvent.PROGRESS , onProgress );
		}

		protected function onComplete( event : Event ) : void
		{
			var loaderInfo : LoaderInfo = event.target as LoaderInfo;
			_module = loaderInfo.content as IModule;
			removeListeners( loaderInfo );
			dispatchEvent( new Event( COMPLETE ));
		}


		protected function onIOError( event : IOErrorEvent ) : void
		{
			//do something
			dispatchEvent( event );
		}

		protected function onProgress( event : Event ) : void
		{
			//do something
			dispatchEvent( event );
		}

		public function get moduleVO() : ModuleVO
		{
			return _moduleVO;
		}

		public function set moduleVO( value : ModuleVO ) : void
		{
			_moduleVO = value;
		}

		public function get module() : IModule
		{
			return _module;
		}

		public function set module( value : IModule ) : void
		{
			_module = value;
		}
	}
}